class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        
        nums.sort()
        n = len(nums)
        ans = sum(nums[:3])
        for i in range(n-2):
            l,r=i+1,n-1
            while l<r:
                cur=nums[i]+nums[l]+nums[r]
                if cur==target:
                    return cur
                elif abs(cur-target)<abs(ans-target):
                    ans=cur
                elif cur>target:
                    r-=1
                elif cur<target:
                    l+=1
        return ans